import update from 'immutability-helper';
import { getEvaluationDirs, getCategories, getEvaluationResult } from '../services/evaluation';

export default {

  namespace: 'evaluation',

  state: {
    dirs: [],
    selectedDir: '',

    category: [],
    selectedCategoryId: null,

    evaluationResult: [],
  },

  subscriptions: {
    setup({ dispatch, history }) {  // eslint-disable-line
    },
  },

  effects: {
    *fetchEvaluationDirs(action, { call, put }) {
      const response = yield call(getEvaluationDirs);
      yield put({
        type: 'save',
        payload: {
          key: 'dirs',
          value: response,
        },
      });
    },
    *fetchCategories({ payload }, { call, put }) {
      const response = yield call(getCategories);
      yield put({
        type: 'save',
        payload: {
          key: 'category',
          value: response,
        },
      });
    },
    *fetchEvaluationResult({ payload }, { call, put, select }) {
      const state = yield select(state => state.evaluation);
      const { selectedDir, selectedCategoryId } = state;
      if(selectedDir && selectedCategoryId){
        const response = yield call(getEvaluationResult, selectedDir, selectedCategoryId);
        yield put({
          type: 'save',
          payload: {
            key: 'evaluationResult',
            value: response,
          },
        });
      }
    },
  },

  reducers: {
    save(state, { payload : { key, value }}) {
      return update(state, { [key] : { $set: value}});
    },
  },

};
